<template>
  <div v-on:click.capture="stopClick($event)" :class="isVisitor == 1 && isWeixin ? 'c-p c-pt80' : ''">
    <!--游客模式提示-->
    <div v-if="isVisitor == 1 && isWeixin" :class="colorName" id="visitorTip" class="c-ph24 c-flex-row c-justify-sb c-aligni-center c-pv16 theme-bg" @click="stopClick($event)">
      <span class="c-fc-white c-fs22">当前为游客模式，登录享受更多精彩服务</span>
      <div class="c-ph18 c-pv4 c-fs22 theme-fc c-bg-white c-br24">立即登录</div>
    </div>
    <nav-bottom-bar :itemIndex="1"></nav-bottom-bar>
    <!--私人定制 炳善易学堂g9zd-->
    <div class="customMade" v-if="companyId == 'g9zd'" @click="goCustomYX">
      <img src="https://kposshzcdn.ckjr001.com/admin/material/9_material_admin/image/assets/i/wap/customMade/g9zd_logo.png" class="c-w100" />
    </div>
    <template v-if="themeName == 'mb1' || themeName == 'mb2' || themeName == 'mb4' || themeName == 'mb5' || themeName == 'mb6'">
      <keep-alive>
        <component :is="hiTemp"></component>
      </keep-alive>
    </template>
    <template v-else-if="themeName == 'mb3'">
      <keep-alive>
        <component :is="hiTemp" :isSign='isSign' :colorName='colorName'></component>
      </keep-alive>
    </template>
    <template v-else-if="themeName == 'mb7' || themeName == 'mb8'">
      <keep-alive>
        <component :is="hiTemp" :tName="themeName"></component>
      </keep-alive>
    </template>
    <my-loading :showLoading="true" v-else></my-loading>
    <!-- 推荐有礼 -->
    <recommend-present v-if="isVisitor != 1" ref="recommendPresent" from="index" @showPresent="showPresent" @alertOnHide="alertOnHide"></recommend-present>
    <open-ad-modal v-if="isVisitor != 1" :isShowAD.sync='isShowAD' :imgAd='imgAd' :adLink='adLink'></open-ad-modal>
    <add-teacher-modal v-if="isVisitor != 1" :teacherQrCode='teacherQrCode'></add-teacher-modal>
    <coupon-modal v-if="showCouponDialog && isVisitor != 1 && !$isWxAppIos()" :adName="adName" :adCoupon="adCoupon" :osId="osId" :recordType="recordType" :showCouponDialog.sync="showCouponDialog"></coupon-modal>
    <!-- 荣誉证书 -->
    <honor-certificate ref="honorcerCom" :isGoAchievem="1"/>
  </div>
</template>

<script>
import NavBottomBar from "@/components/templates/common/navBottomBar.vue";
import myLoading from "@/plugin/loading/loading.vue";
import recommendPresent from '@/components/templates/recommendPresent'
import openAdModal from "@/components/templates/homeIndex/openAdModal.vue";
import addTeacherModal from "@/components/templates/homeIndex/addTeacherModal.vue";
import couponModal from "@/components/templates/couponModal.vue";
import { utilJs } from "@/utils/common.js";
import honorCertificate from "@/components/templates/learnAndachCer/honorCertificate.vue";
export default {
  name: "Index",
  components: {
    NavBottomBar,
    myLoading,
    recommendPresent,
    openAdModal,
    addTeacherModal,
    couponModal,
    honorCertificate
  },
  props: [],
  data() {
    return {
      companyId: localStorage.getItem("companyId"),
      themeName: "", //localStorage.getItem("themeName"),
      colorName: localStorage.getItem("colorName"),
      ad: 1,
      isSign: true,
      teacherQrCode: "",
      imgAd: "",
      adLink: "",
      adName: "",
      adCoupon: [],
      isShowAD: false,
      showCouponDialog: false,
      showCouponDialogflag: false,
      // navigateList: [],
      osId: "",
      hiTemp: null,
      isVisitor: localStorage.getItem("isVisitor") || 0, //1是游客
      isWeixin: false, // 是否是微信浏览器
    };
  },
  created() {
    utilJs.appShare(this);
  },
  mounted() {},
  methods: {
    lastHonor() {
      let postUrl = `${global.apiurl}Certificate/lastHonor`;
      utilJs.getMethod(postUrl, res => {
        if (res.cardId) {
          this.$refs.honorcerCom.public_open({id:res.id, cardId:res.cardId})
        }
      });
    },
    //游客模式点击详情进行跳转到授权页面
    stopClick(event) {
      if (localStorage.getItem("isVisitor") && localStorage.getItem("isVisitor") == 1 && window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger' && window.navigator.userAgent.toLowerCase().match(/wxwork/i) != "wxwork" && localStorage.getItem("wxAppEnvironment") != 'wxwork') {
        let e = event || window.event;
        if (e.stopPropagation) {
          e.stopPropagation();
        } else {
          e.cancelBubble = true;
        }
        this.$routerGo(this, "push", { path: '/homePage/login/wechatAuthPage', query: { refereeId: this.$route.query.refereeId, prodId: this.$route.query.prodId, prodType: this.$route.query.prodType } });
      }
    },
    //私人订制 g9zd
    goCustomYX: function () {
      //if (localStorage.getItem("companyId") == "g9zd") {
      let $this = this;
      utilJs.postMethod(global.apiurl + "extend/submitOrder", {}, function (res) {
        let orderId = res.orderId;
        //let uHref = res.url+'?Authorization=Bearer '+localStorage.getItem("token");
        let uHref = global.apiurl + res.url + '?userId=' + localStorage.getItem("userId");
        if (orderId != -1) {
          $this.wePay(orderId, uHref);
        } else {
          utilJs.locationHref(uHref);
        }
      }, function () { });
      //}
    },
    wePay: function (orderId, uHref) {
      if (orderId != -1) {
        let data = {
          orderId: orderId
        };
        if (sessionStorage.getItem('promotedAccountId')) {
          data.promotedAccountId = sessionStorage.getItem('promotedAccountId')
        }
        utilJs.wechatPay(
          data,
          function () {
            utilJs.locationHref(uHref);
          },
          function () { }
        );
      }
    },
    appShare: function () {
      utilJs.appShareTrue("", "", "", "");
    },
    //作为分享页被推荐人进入
    isRecommendPage() {
      let recRelateId = this.$route.query.recRelateId; //推荐人ID
      let recType = this.$route.query.recType; //推荐类型 1 访问 2 绑定 3 支付
      let bindPhone = this.$route.query.bindPhone; //完成推荐绑定手机号
      let data = { relateId: recRelateId };
      if (!recRelateId) {
        this.showCouponDialog = this.showCouponDialogflag;
        return;
      }
      if (recType == 1) {
        this.$refs.recommendPresent.completetRecommendTask(data); // 调用子组件方法
        return;
      }
      if (recType == 2) {
        if (bindPhone || localStorage.getItem("bindPhone")) {
          if (localStorage.getItem("bindPhone")) {
            localStorage.removeItem("bindPhone")
          }
          data.mobile = localStorage.getItem("uMobile");
          this.$refs.recommendPresent.completetRecommendTask(data); // 调用子组件方法
        } else if (!localStorage.getItem("uMobile")) {
          utilJs.goBindMobile({
              recRelateId: recRelateId,
              recType: recType,
              goHomeIndex: 1,
            });
        } else {
          this.$cjConfirm({
            title: '领取失败',
            message: '您已绑定过手机号，不在推荐范围，无法领取奖励',
            showCancelButton: false,
          })
        }
      }
    },
    alertOnHide(info) { // 推荐有礼领取失败的弹框消失事件
      this.showCouponDialog = this.showCouponDialogflag;
    },
    showPresent(data) { // 推荐有礼礼包出现的时候执行
      this.showCouponDialog = false;
    },
    registerComponent(themeName) {
      switch (themeName) {
        case "mb1":
        case "mb2":
        case "mb5":
          this.hiTemp = () => ({
            component: import("@/components/templates/homeIndex/indexFive.vue")
          })
          break;
        case "mb3":
          this.hiTemp = () => ({
            component: import("@/components/templates/homeIndex/indexThree.vue")
          })
          break;
        case "mb4":
          this.hiTemp = () => ({
            component: import("@/components/templates/homeIndex/indexFour.vue")
          })
          break;
        case "mb6":
          this.hiTemp = () => ({
            component: import("@/components/templates/homeIndex/indexSix.vue")
          })
          break;
        case "mb7":
        case "mb8":
          this.hiTemp = () => ({
            component: import("@/components/templates/homeIndex/indexSeven.vue")
          })
          break;
        default:
          this.hiTemp = () => ({
            component: import("@/components/templates/homeIndex/indexSeven.vue")
          })
      }
    },
    getCarousel() {
      let that = this;
      // this.ad = this.$route.query.ad ? Number(this.$route.query.ad) : 0;
      utilJs.getMethod(`${global.apiurl}company/getCarousel${that.$isWxApp() ? '?isMiniHomePage=1' : ''}`, (res) => {
        that.companyId = localStorage.getItem("companyId");
        that.themeName = res.company.themeName;
        if (that.themeName != localStorage.getItem("themeName") || that.hiTemp == null) {
          if (localStorage.getItem("isVisitor") && localStorage.getItem("isVisitor") == 1) {
            setTimeout(() => {
              that.registerComponent(that.themeName);
            }, 30);
          } else {
            that.registerComponent(that.themeName);
          }
        }
        that.colorName = res.company.colorName;
        localStorage.setItem("themeName", that.themeName);
        localStorage.setItem("colorName", that.colorName);
        that.isSign = res.pointSign != 0;
        // that.swiperList = res.carousel;
        that.teacherQrCode = res.company.teacherQrcode;
        if (res.company.companyName) {
          setDocumentTitle(res.company.companyName);// eslint-disable-line
        } else {
          setDocumentTitle('首页');// eslint-disable-line
        }
        localStorage.setItem("gzqr" + localStorage.getItem("companyId"), res.company.mpQrcode);
        that.osId = res.company.osId;
        that.adCoupon = res.company.adCoupon;
        let couponDialogList = localStorage.getItem("showCouponDialog") ? JSON.parse(localStorage.getItem("showCouponDialog")) : [];
        if (couponDialogList.includes(that.osId)) {
          that.showCouponDialog = false;
        } else {
          //是否有开屏优惠券
          let isShowCoupon = res.company.showOpenScreenAd == 1 && res.company.adType == 2 && that.adCoupon.length > 0;
          //是否第一次获取到这个优惠券，不相等的标识第一次获取到，不管有没有显示过，都要显示，相等就要看是否显示过该优惠券
          let isNeedAd = that.osId != localStorage.getItem('lastOs');
          that.showCouponDialogflag = isShowCoupon && (isNeedAd || that.ad)
        }
        that.adName = res.company.adName;
        that.imgAd = res.company.adImg;
        that.adLink = res.company.adLink;
        that.recordType = res.company.recordType;
        if (that.adCoupon && that.adCoupon.length > 0) {
          that.adCoupon.forEach((item) => {
            if (item.validStatus != 1 && item.validStatus != 2) { //领取后开始计算有效期和领取次日开始计算有效期的，startAt和endAt为null
              item.startAt = item.startAt.substr(0, 10).replace(/-/g, ".");
              item.endAt = item.endAt.substr(0, 10).replace(/-/g, ".");
            }
            item.couponNum = 1; //首页开屏广告优惠券数量返回不正确（后端本期暂不处理），所以先不展示
          })
        }
        let isShowAD = res.company.showOpenScreenAd == 1 && that.ad == 1 && res.company.adType == 1 && !that.$route.query.recRelateId;
        //若今日已显示过开屏广告，则不显示，每天凌晨12点清空
        // if (isShowAD) {
        //   let todayDate = utilJs.getNowTimeFormat('YYYY-MM-DD');
        //   let hasShow = localStorage.getItem('todayShowAD') == todayDate;
        //   isShowAD = hasShow ? false : true;
        //   localStorage.setItem('todayShowAD', todayDate)
        // }
        that.isShowAD = isShowAD;
        that.isRecommendPage(); // 推荐有礼
      });
    }
  },
  activated() {
    setDocumentTitle('首页');// eslint-disable-line
    this.osId = "";
    this.showCouponDialog = false;
    this.showCouponDialogflag = false;
    this.isShowAD = false;
    this.hiTemp = null;
    this.isWeixin = utilJs.isWeiXin() && window.navigator.userAgent.toLowerCase().match(/wxwork/i) != "wxwork" && localStorage.getItem("wxAppEnvironment") != 'wxwork';
    if (localStorage.getItem("themeName")) {
      this.registerComponent(localStorage.getItem("themeName"));
    }
    let timer = null;
    // 防止安卓app，首次进入可能会没有取到h5的token就请求接口，导致接口报错
    if (!localStorage.getItem(localStorage.getItem("companyId") + "|token")) {
      timer = setTimeout(() => {
        this.getCarousel();
        clearTimeout(timer);
      }, 300);
    } else {
      this.getCarousel();
    }

    // 防止偶现--取不到发售版缓存，跳到其他版本首页，应跳到发售列表（发售版首页）
    let fashouTimer = null;
    fashouTimer = setTimeout(() => {
      const isFaShou = localStorage.getItem("isFaShou") == 1;
      const p = '/fashou/activity';
      if (isFaShou) {
        this.$router.replace(p)
      }
      clearTimeout(fashouTimer);
    }, 500)
    this.lastHonor()
  },
  deactivated() {
    // this.ad = 0;
    this.showCouponDialog = false;
    this.isShowAD = false;
    localStorage.setItem(`lastOs`, this.osId);
  },
  beforeRouteLeave(to, from, next) {
    if (to.path != '/homePage/login/bindMobile') {
      this.ad = 0; //开屏广告领取优惠券如果需要绑定手机号，绑定后跳回首页需要弹出开屏广告优惠券
    }
    next();
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#visitorTip {
  position: fixed;
  max-width: 16rem;
  margin: 0 auto;
  top: 0;
  width: 100%;
  z-index: 1;
}
.customMade {
  width: 2rem;
  position: fixed;
  bottom: 3rem;
  right: 0.5rem;
  z-index: 999;
}
.family-card-bg {
  background: url("../assets/i/wap/vip/familyCard.png");
  background-size: cover;
  padding-left: 3.45rem;
  padding-right: 0.35rem;
}
.equity-vip-bg {
  background: url("../assets/i/wap/recommend/VIP.png");
  background-size: cover;
  padding-left: 3.45rem;
  padding-right: 0.35rem;
}
.equity-svip-bg {
  background: url("../assets/i/wap/recommend/SVIP.png");
  background-size: cover;
  padding-left: 3.45rem;
  padding-right: 0.35rem;
}
.dia-head-bg {
  padding-top: 5rem;
}
.dialog-mid {
  background: url("../assets/i/wap/recommend/recommend-present-mid.png")
    no-repeat;
  background-size: 100% 100%;
  padding-right: 0.4rem;
}
.coupon-mb1 {
  background: url("../../public/i/wap/vip/coupon-mb1.png");
  background-size: cover;
}
.exchange-left1 {
  background: url("../../public/i/wap/coupon/exchange.png") no-repeat 100%;
  background-size: 100% 100%;
}
.c-bg-A71 {
  background-color: #a0701c;
  opacity: 0.2;
  border-radius: 50%;
}
</style>

